package org.hiucung.desktoptranslationtools.screens

import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.FilledTonalButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import cafe.adriel.voyager.core.screen.Screen
import org.hiucung.desktoptranslationtools.bean.DialogEvent
import org.hiucung.desktoptranslationtools.bean.ExportResult
import org.hiucung.desktoptranslationtools.dialog.MaterialDialog
import org.hiucung.desktoptranslationtools.dialog.openDirectorDialog
import org.hiucung.desktoptranslationtools.dialog.openSaveFileDialog
import org.hiucung.desktoptranslationtools.viewmodel.ExportViewModel

/**
 * @title: ExportScreen
 * @projectName DesktopTranslationTools
 * @description: 导出页面
 * @author Kicc
 * @date 2025/7/22 2:35
 */
class ExportScreen : Screen {

    @Composable
    override fun Content() {
        val exportViewModel = remember { ExportViewModel() }
        val selectedPath by exportViewModel.selectedDirectoryPath.collectAsState()
        val savePath by exportViewModel.saveTranslationPath.collectAsState()

        // 弹窗状态控制
        var dialogEvent by remember { mutableStateOf<DialogEvent?>(null) }

        // 使用 LaunchedEffect监听一次性弹窗事件
        LaunchedEffect(Unit) {
            exportViewModel.dialogEvent.collect { event ->
                dialogEvent = event
            }
        }

        // 显示弹窗
        dialogEvent?.let { event ->
            MaterialDialog(
                event = event,
                onDismiss = { dialogEvent = null }
            )
        }

        val isLoading by exportViewModel.isLoading.collectAsState()
        var showResultDialog by remember { mutableStateOf<ExportResult?>(null) }

        // 监听导出结果事件
        LaunchedEffect(Unit) {
            exportViewModel.exportEvent.collect { result ->
                showResultDialog = result
            }
        }

        Column(
            modifier = Modifier
                .padding(16.dp)
                .verticalScroll(rememberScrollState())
        ) {
            // 根目录选择部分
            SectionTitle("项目根目录选择")
            Text(
                text = "请在文件选择器中选择项目的根目录路径",
                style = MaterialTheme.typography.bodyMedium,
                modifier = Modifier.padding(bottom = 8.dp)
            )

            PathSelectionRow(
                label = "根目录路径:",
                path = selectedPath,
                buttonText = "选择目录",
                onButtonClick = {
                    exportViewModel.updateSelectedDirectory(openDirectorDialog())
                }
            )

            Spacer(modifier = Modifier.height(24.dp))

            // 导出路径选择部分
            SectionTitle("翻译文件导出设置")
            Text(
                text = "请选择翻译文件导出的路径和文件名",
                style = MaterialTheme.typography.bodyMedium,
                modifier = Modifier.padding(bottom = 8.dp)
            )

            PathSelectionRow(
                label = "导出路径:",
                path = savePath,
                buttonText = "选择文件",
                onButtonClick = {
                    openSaveFileDialog(
                        title = "请选择Excel表格文件保存路径",
                        description = "Excel表格文件",
                        selectFilePath = { filePath ->
                            filePath.takeIf { it.isNotEmpty() }?.run {
                                exportViewModel.updateSaveTranslationPath(this)
                            }
                        },
                        suffixNames = arrayOf("xlsx", "xls")
                    )
                }
            )

            Spacer(modifier = Modifier.height(32.dp))

            // 导出按钮
            Button(
                onClick = {
                    if (selectedPath.isEmpty()) {
                        exportViewModel.showErrorMessage("请选择根目录路径！")
                    } else if (savePath.isEmpty()) {
                        exportViewModel.showErrorMessage("请选择翻译导出路径！")
                    } else {
                        exportViewModel.exportToExcel()
                    }
                },
                modifier = Modifier
                    .fillMaxWidth()
                    .height(48.dp),
                shape = MaterialTheme.shapes.medium,
                colors = ButtonDefaults.buttonColors(
                    containerColor = MaterialTheme.colorScheme.primary
                )
            ) {

                // 正在导出状态时，按钮内部展示一个转圈圈的效果
                if (isLoading) {
                    CircularProgressIndicator(
                        modifier = Modifier.size(24.dp),
                        color = MaterialTheme.colorScheme.onPrimary,
                        strokeWidth = 2.dp
                    )
                } else {
                    Text(
                        text = "导出翻译文件",
                        style = MaterialTheme.typography.labelLarge
                    )
                }
            }

            // 结果弹窗
            showResultDialog?.let { result ->
                ExportResultDialog(
                    result = result,
                    onDismiss = { showResultDialog = null }
                )
            }
        }
    }

    @Composable
    private fun SectionTitle(text: String) {
        Text(
            text = text,
            style = MaterialTheme.typography.titleMedium,
            color = MaterialTheme.colorScheme.primary,
            modifier = Modifier.padding(bottom = 8.dp)
        )
    }

    @Composable
    private fun PathSelectionRow(
        label: String,
        path: String,
        buttonText: String,
        onButtonClick: () -> Unit
    ) {
        Row(
            verticalAlignment = Alignment.CenterVertically,
            modifier = Modifier.padding(vertical = 8.dp)
        ) {
            Text(
                text = label,
                style = MaterialTheme.typography.bodyMedium,
                modifier = Modifier.weight(1f)
            )

            Spacer(modifier = Modifier.width(8.dp))

            Text(
                text = path.ifEmpty { "未选择" },
                style = MaterialTheme.typography.bodySmall,
                color = if (path.isEmpty()) MaterialTheme.colorScheme.onSurface.copy(alpha = 0.6f)
                else MaterialTheme.colorScheme.onSurface,
                modifier = Modifier.weight(2f)
            )

            Spacer(modifier = Modifier.width(16.dp))

            Button(
                onClick = onButtonClick,
                shape = MaterialTheme.shapes.small,
                colors = ButtonDefaults.outlinedButtonColors()
            ) {
                Text(buttonText)
            }
        }
    }

    @Composable
    private fun ExportResultDialog(
        result: ExportResult,
        onDismiss: () -> Unit
    ) {
        AlertDialog(
            onDismissRequest = onDismiss,
            shape = MaterialTheme.shapes.extraLarge,
            title = {
                Text(
                    text = when (result) {
                        is ExportResult.Success -> "完成"
                        is ExportResult.Error -> "错误"
                    },
                    style = MaterialTheme.typography.headlineSmall
                )
            },
            text = {
                Text(
                    text = when (result) {
                        is ExportResult.Success -> result.message
                        is ExportResult.Error -> result.error
                    },
                    style = MaterialTheme.typography.bodyMedium
                )
            },
            confirmButton = {
                FilledTonalButton(
                    onClick = onDismiss,
                    colors = ButtonDefaults.filledTonalButtonColors(
                        containerColor = when (result) {
                            is ExportResult.Success ->
                                MaterialTheme.colorScheme.primaryContainer
                            is ExportResult.Error ->
                                MaterialTheme.colorScheme.errorContainer
                        }
                    )
                ) {
                    Text("确定")
                }
            }
        )
    }
}